/*
 * @lc app=leetcode.cn id=503 lang=typescript
 *
 * [503] 下一个更大元素 II
 */

// @lc code=start
function nextGreaterElements(nums: number[]): number[] {
  const stack: number[] = [];
  const ans: number[] = new Array(nums.length).fill(-1);
  // 循环数组
  const temp = [...nums, ...nums];
  for (let i = 0; i < temp.length; i++) {
    while (stack.length && temp[i] > temp[stack[stack.length - 1]]) {
      let idx = stack.pop();
      ans[idx] = temp[i];
    }
    stack.push(i);
  }

  // 只取一个数组的结果
  return ans.slice(0, nums.length);
}
// @lc code=end
